﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;

namespace Xss.Logging.Simple
{
    public class FileLogger : Logger
    {

        public FileLogger(string logName, IDictionary properties)
            : base(logName, properties)
        {

        }

        protected override void WriteInternal(LogLevel level, object message, Exception exception)
        {
            StringBuilder sb = new StringBuilder();
            FormatOutput(sb, level, message, exception);
            ValidFile(sb.ToString());
        }

        static object _sync = new object();

        void ValidFile(string log)
        {
            var folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
            if (!Directory.Exists(folder))
                Directory.CreateDirectory(folder);
            var file = Path.Combine(folder, string.Format("{0}.log", DateTime.Now.ToString("yyyyMMdd")));

            lock (_sync)
            {
                Stream fs = null;
                if (!File.Exists(file))
                {
                    fs = File.Create(file);
                }
                else
                {
                    fs = File.Open(file, FileMode.Append, FileAccess.Write);
                }

                using (fs)
                {
                    WriteToFile(fs, log);
                }
            }
        }

        void WriteToFile(Stream fs, string log)
        {
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(log)))
            {
                ms.CopyTo(fs);
            }
        }
    }
}
